package com.zzyl.nursing.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author xiaochang
 * @date 2025-07-25
 */
@Slf4j
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        checkIn.setCreateTime(DateUtils.getNowDate());
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        checkIn.setUpdateTime(DateUtils.getNowDate());
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteByIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void apply(CheckInApplyDto dto) {
        //1. 检查老人是否已经入住，如果已经入住，直接结束
        String idCardNo = dto.getCheckInElderDto().getIdCardNo();
        QueryWrapper<Elder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id_card_no",idCardNo);
        Elder elder = elderMapper.selectOne(queryWrapper);
        if(elder != null && elder.getStatus() != 1 && elder.getStatus() != 5){
            throw new RuntimeException("该老人已经入住");
        }
        //2.占用床位 status=1
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        if(bed == null || bed.getBedStatus() != 0){
            throw new RuntimeException("该床位已占用");
        }else {
            bed.setBedStatus(1);
        }
        bedMapper.updateById(bed);
        //3.新增或者修改老人信息
        if (elder == null){
            elder=new Elder();
            BeanUtil.copyProperties(dto.getCheckInElderDto(),elder);
            elder.setStatus(1);
            elder.setCreateTime(DateUtils.getNowDate());
            elder.setBedId(bed.getId());
            elder.setBedNumber(bed.getBedNumber());
            elderMapper.insert(elder);

        }
        //4.新增签约办理
        Contract contract = new Contract();
        BeanUtil.copyProperties(dto.getCheckInContractDto(),contract);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setCreateTime(DateUtils.getNowDate());
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        contract.setStatus((long) (contract.getStartDate().isAfter(LocalDateTime.now())?1:0));//0:未开始，1:进行中，2:已结束
        contractMapper.insert(contract);
        //5.新增入住信息
         CheckIn checkIn = new CheckIn();
         BeanUtil.copyProperties(dto.getCheckInConfigDto(),checkIn);
         checkIn.setElderId(elder.getId());
         checkIn.setElderName(elder.getName());
         checkIn.setIdCardNo(elder.getIdCardNo());
         checkIn.setBedNumber(bed.getBedNumber());
         checkIn.setStatus(1L);
         checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
         checkInMapper.insert(checkIn);
        //6.新增入住配置
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtil.copyProperties(dto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);

    }

    @Override

    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo=new CheckInDetailVo();

        CheckIn checkIn=checkInMapper.selectCheckInById(id);

        //查询老人信息
        Elder elder= elderMapper.selectElderById(checkIn.getElderId());
        CheckInElderVo checkInElderVo=new CheckInElderVo();
        BeanUtil.copyProperties(elder,checkInElderVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        log.info("查询老人信息{}",elder);
        //查询家属信息
        List<ElderFamilyVo> elderFamilyVoList=new ArrayList<>();
        elderFamilyVoList=JSONUtil.toList(checkIn.getRemark(),ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);

        //查询入住配置
        QueryWrapper<CheckInConfig> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("check_in_id",id);
        CheckInConfig checkInConfig=checkInConfigMapper.selectOne(queryWrapper);

        CheckInConfigVo checkInConfigVo=new CheckInConfigVo();
        BeanUtil.copyProperties(checkInConfig,checkInConfigVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);

        ////查询签约办理
        Contract contract=contractMapper.selectContractByElderId(elder.getId());
        //ContractVo contractVo=new ContractVo();
        //BeanUtil.copyProperties(contract,contractVo);
        checkInDetailVo.setContract(contract);
        //和一块发送


        return checkInDetailVo;
    }

}
